<template>
  <a-form :label-col="labelCol" layout="inline">
    <a-form-item label="搜索">
      <a-input v-model:value="selectName"/>
    </a-form-item>
    <a-form-item>
      <!--查询-->
      <a-button type="primary" @click="toSelect">查询</a-button>
    </a-form-item>
    <!--  新增-->
    <a-form-item>
      <a-button type="primary" @click="showModal">新增</a-button>
    </a-form-item>
  </a-form>

  <a-layout>
    <!--右侧内容 数据渲染表格-->
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <div class="about">
        <!--        <a-button type="primary" @click="showModal">-->
        <!--          新增-->
        <!--        </a-button>-->
        <a-table :columns="columns" :row-key="item => item.id" :data-source="ebooks" :pagination="pagination"
                 :loading="isLoading" @change="handleTableChange">
          <template #bodyCell="{ column, text,record }">
            <template v-if="column.dataIndex === 'cover'">
              <img :src="text" alt="封面"/>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-space size="small">
                <router-link to="/admin/doc">
                  <a-button type="primary">
                    文档
                  </a-button>
                </router-link>
                <a-button type="primary" @click="showModal(record)">
                  编辑
                </a-button>
                <a-popconfirm title="确认要删除此项数据吗?" ok-text="Yes" cancel-text="No" @confirm="confirm(record)"
                              @cancel="cancel">
                  <a-button danger>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-layout-content>
  </a-layout>
  <!-- 增删弹窗-->
  <a-modal v-model:open="open" title="Title" :confirm-loading="confirmLoading" @ok="handOk">
    <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="封面" name="cover">
        <a-input v-model:value="formState.cover"/>
      </a-form-item>
      <a-form-item label="名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入作者"/>
      </a-form-item>
      <a-form-item label="分类" name="categoryIds">
        <a-cascader v-model:value="categoryIds" :options="options" :fieldNames="fieldNames" expand-trigger="hover"
                    placeholder="选择分类"/>
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-input v-model:value="formState.description" placeholder="请输入描述"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <!--  错误提醒弹窗-->
  <context-holder/>
</template>
<script setup lang="ts">
import {onMounted, ref, reactive, computed, toRaw, UnwrapRef} from 'vue';
import axios from 'axios';
import {message} from 'ant-design-vue';
import type {CascaderProps} from 'ant-design-vue';
import {arrayToTree} from '@/utils/tools';

// 表格结构
const columns = [
  {
    title: '封面',
    dataIndex: 'cover',
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '分类',
    key: 'category',
    customRender:({record}:any)=>{
      const category1 = options.value?.find((item:any) => item.id === record.category1Id);
      const category2 = category1?.children?.find((item:any) => item.id === record.category2Id);
      return category1&& category2?category1.name+'/'+category2.name:'无';
    }
  },

  // {
  //   title: '文档数',
  //   dataIndex: 'docCount'
  // },
  // {
  //   title: '阅读数',
  //   dataIndex: 'viewCount'
  // },
  // {
  //   title: '点赞数',
  //   dataIndex: 'voteCount'
  // },
  {
    title: '描述',
    dataIndex: 'description',
  },
  {
    title: '操作',
    dataIndex: 'action',
  }
];
// 表格数据
const ebooks = ref([]);
//分页信息
const pagination = ref({
  pageSize: 5,
  total: 0,
  current: 1
})

// 数据加载状态
const isLoading = ref(true)
// 页面加载时，请求数据
onMounted(async () => {
  render()
})

// 渲染表格数据
function render() {
  axios.get('/ebook/selectByPage', {
    params: {
      page: pagination.value.current,
      size: pagination.value.pageSize
    }
  }).then(res => {
    console.log(res.data.data.list.length)
    if (res.data.data.list.length == 0) {
      pagination.value.current = pagination.value.current - 1;
      render()
    }
    // 加载完成
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    ebooks.value = res.data.data.list;
  })
}

//  表格分页
const handleTableChange = (pag: any) => {
  console.log('handleTableChange', pagination)
  pagination.value.current = pag.current;
  render()
}
const modalText = ref<string>('Content of the modal');
const open = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
// 表单
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
// 编辑数据显示弹窗
const showModal = (record: any) => {
  open.value = true;
  //  弹窗内容
  // modalText.value = JSON.stringify(record);
  //  弹窗内容
  console.log(record.id)
  if (record.id != null) {
    formState.id = record.id;
  }
  formState.cover = record.cover;
  formState.name = record.name;
  formState.category1Id = record.category1Id;
  formState.category2Id = record.category2Id;
  formState.description = record.description;
  categoryIds.value = [record.category1Id, record.category2Id];
};

// 表单类型
interface ebookFormState {
  id: number;
  cover: string;
  name: string;
  category1Id: number;
  category2Id: number;
  description: string;
}

// 表单数据
const formState = reactive<ebookFormState>({
  id: 0,
  cover: '',
  name: '',
  category1Id: 0,
  category2Id: 0,
  description: ''
})


const [messageApi, contextHolder] = message.useMessage();

function handOk() {
  modalText.value = 'The modal will be closed after two seconds';
  confirmLoading.value = true;
  formState.category1Id = +categoryIds.value[0];
  formState.category2Id = +categoryIds.value[1];
  axios.post('/ebook/saveOrUpdate', formState).then((res: { data: { code: number; }; }) => {
    if (res.data.code === 200) {
      //  关闭弹窗
      open.value = false;
      confirmLoading.value = false;
      //  重新请求数据
      render();
      messageApi.info("操作成功");
    }
  }).catch((error: { response: { status: any; data: any; headers: any; }; request: any; message: any; }) => {
    if (error.response) {
      //  关闭弹窗,提示错误信息
      open.value = false;
      confirmLoading.value = false;
      console.log(error.response.data);
      messageApi.info(error.response.data.errors[0].defaultMessage);
    }
    // else if (error.request) {
    //   // 请求已发送，但没有收到响应
    //   console.error('Request:', error.request);
    // } else {
    //   // 在设置请求时发生错误
    //   console.error('Error Message:', error.message);
    // }
  })
}

//删除确认和取消弹窗
const confirm = (record: any) => {
  console.log(record.id);
  axios.post('/ebook/deleteById/' + record.id).then(() => {
    // 加载完成
    isLoading.value = false;
    message.success('删除成功');
    // mySafeAsyncFunction()
    render()
  })
};
//取消删除
const cancel = (record: any) => {
  console.log(record.id);
  message.error('取消删除');
};
const selectName = ref("");
const toSelect = () => {
  axios.get('/ebook/selectByPage', {
    params: {
      page: pagination.value.current,
      size: pagination.value.pageSize,
      name: selectName.value
    }
  }).then(res => {
    console.log(res.data.data.list.length)
    if (res.data.data.list.length == 0) {
      pagination.value.current = pagination.value.current - 1;
      render()
    }
    // 加载完成
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    ebooks.value = res.data.data.list;
  })
  console.log('submit!', selectName);
};

const categoryIds = ref<string[]>([]);
const options = ref<CascaderProps['options']>([]);
// 定义fieldNames字段名
const fieldNames: CascaderProps['fieldNames'] = {
  value: 'id',
  label: 'name',
  children: 'children'
};

// 加载分类数据
const fetchCategorys = async () => {
  // 加载中
  isLoading.value = true;
  // 清空数据
  await axios.get('/category/selectByPage', {
    params: {
      page: 1,
      size: 100
    }
  }).then(res => {
    //  请求成功
    if (res.data.code === 200) {
      //  将数据转换为树形结构
      options.value = arrayToTree(res.data.data.list);
    }
  })
}
//  页面加载完成后请求数据
const fetchCategoryAndEbooks = async () => {
  await fetchCategorys();
  render();
};
onMounted(fetchCategoryAndEbooks);

</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

img {
  width: 50px;
  height: 50px;
}
</style>